package com.yuezhu.versionup;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;


/**
 * 活动下载任务队列,储存的为UUID
 *
 */
public class ActivityTaskQueue {

	private Queue<String> queue;
	private int maxQueueSize = 10000;

	private static class ContextQueueHolder {
		private static ActivityTaskQueue instance = buildSingleton();

		private static ActivityTaskQueue buildSingleton() {
			return new ActivityTaskQueue();
		}
	}

	public static ActivityTaskQueue getInst() {
		return ContextQueueHolder.instance;
	}

	private ActivityTaskQueue() {
		this.queue = new LinkedBlockingQueue<String>(maxQueueSize);
	}

	/**
	 * 添加下载队列
	 * @param message
	 */
	public void addMessage(String message) {
		//先判断有没有此任务
		if(!queue.contains(message)){
			queue.offer(message);
		}
	}

	/**
	 * 获取队列
	 * @param timeoutInMillionSeconds
	 * @return
	 * @throws InterruptedException
	 */
	public String getMessage(int timeoutInMillionSeconds)
			throws InterruptedException {
		if (queue.isEmpty()) {
			Thread.sleep(timeoutInMillionSeconds);
		}
		if (queue.isEmpty()) {
			throw new InterruptedException("wait timeout");
		}
		return queue.poll();
	}

	/**
	 * 移除指定任务
	 * @param uuid
	 */
	public void remove(String uuid){
		if(queue.contains(uuid)){
			queue.remove(uuid);
		}
	}

	/**
	 * 判断是否存在
	 * @param uuid
	 * @return
	 */
	public boolean existUUID(String uuid){
		return queue.contains(uuid);
	}
	public int size() {
		return queue.size();
	}

	public void setMaxQueueSize(int maxQueueSize) {
		this.maxQueueSize = maxQueueSize;
	}

	public int getMaxQueueSize() {
		return maxQueueSize;
	}
}
